package com.xingfly.web;

import com.xingfly.model.User;
import com.xingfly.model.vo.UserFromVo;
import com.xingfly.repository.RoleRepository;
import com.xingfly.service.AccountService;
import com.xingfly.service.CaptchaService;
import com.xingfly.service.FollowService;
import com.xingfly.service.PostService;
import com.xingfly.util.PageUtil;
import com.xingfly.web.model.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;

/**
 * Created by SuperS on 29/12/2016.
 */
@RestController
@RequestMapping("users")
public class UserController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private FollowService followService;
    @Autowired
    private PostService postService;
    @Autowired
    private CaptchaService captchaService;

    /**
     * 分页获取用户
     *
     * @param request request参数
     */
    @GetMapping
    public ResponseModel<?> getUsers(@RequestParam(value = "page", required = false) String pageStr, @RequestParam(value = "size", required = false) String sizeStr) {
        Integer page = null;
        Integer size = null;
        try {
            page = PageUtil.parsePage(pageStr);
            size = PageUtil.parseSize(sizeStr);
        } catch (NumberFormatException e) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "参数格式错误!");
        }
        Page<User> userPage = accountService.getUsers(new PageRequest(page - 1, size));

        return ResponseModel.ok(userPage);
    }

    /**
     * 获取单个用户
     *
     * @param id id
     */
    @GetMapping("{id}")
    public ResponseModel<User> getUser(@PathVariable("id") Long id) {
        return ResponseModel.ok(accountService.find(id));
    }

    /**
     * 关闭用户(需要管理员权限)
     *
     * @param id 用户id
     */
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("{id}")
    public ResponseModel<?> closeUser(@PathVariable("id") Long id) {
        User user = accountService.find(id);
        accountService.closeUser(user);
        return ResponseModel.create(null, HttpStatus.OK, "关闭成功!");
    }

    /**
     * 创建用户
     *
     * @param user 用户
     */
    @PostMapping
    public ResponseModel<?> create(@RequestBody UserFromVo userVo,
                                   HttpServletRequest request) {
        User saveUser = null;
        User user = new User();
        user.setUsername(userVo.getUsername());
        user.setMail(userVo.getEmail());
        user.setPassword(userVo.getPassword());
        user.setNickname(userVo.getUsername());
        user.setPhone(userVo.getPhone());
        System.out.println(user);

        //普通用户权限
        user.setRoles(Collections.singletonList(roleRepository.findOne(2L)));
        //开启用户
        user.setEnable(true);
        //用户头像
        user.setAvatar("http://pic.xingfly.com/tx2.jpg");
        user.setLastPasswordResetDate(new Date());

        if (StringUtils.isEmpty(user.getMail())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "邮箱不能为空");
        }
        if (StringUtils.isEmpty(user.getUsername())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "用户名不能为空");
        }
        if (StringUtils.isEmpty(user.getNickname())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "用户昵称不能为空");
        }
        if (StringUtils.isEmpty(user.getPassword())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "用户密码不能为空");
        }
        if (StringUtils.isEmpty(userVo.getCaptcha())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "验证码不能为空");
        }
        if (accountService.find(userVo.getUsername()) != null) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "此用户名已注册");
        }
        if (accountService.findByEmail(userVo.getEmail()) != null) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "此用户邮箱已注册");
        }
//        if (accountService.findByPhone(userVo.getPhone()) != null) {
//            return ResponseModel.error(HttpStatus.BAD_REQUEST, "此手机号已注册");
//        }
        String serverCaptcha = captchaService.get(CaptchaService.KEY_ACCOUNT, userVo.getEmail());
        if (StringUtils.isEmpty(serverCaptcha)) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "验证码失效");
        }
        if (captchaService.verification(userVo.getCaptcha(), serverCaptcha)) {
            user.setLastPasswordResetDate(new Date());
            saveUser = accountService.save(user);
            captchaService.delete(CaptchaService.KEY_ACCOUNT, request.getSession().getId());
        } else {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "验证码错误!");
        }
        return ResponseModel.create(saveUser, HttpStatus.OK);
    }

    /**
     * 忘记密码
     */
    @PostMapping("forgot")
    public ResponseModel<?> forgot(@RequestBody UserFromVo userFromVo,
                                   HttpServletRequest request) {
        if (StringUtils.isEmpty(userFromVo.getUsername())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "用户名不能为空");
        }
        if (StringUtils.isEmpty(userFromVo.getPassword())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "用户密码不能为空");
        }
        if (StringUtils.isEmpty(userFromVo.getCaptcha())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "验证码不能为空");
        }
        if (StringUtils.isEmpty(userFromVo.getEmail())) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "用户邮箱不能为空");
        }
        User user = accountService.find(userFromVo.getUsername());
        if (user != null) {
            if (!user.getMail().equals(userFromVo.getEmail())) {
                return ResponseModel.error(HttpStatus.BAD_REQUEST, "账户和邮箱不匹配");
            }
            String serverCaptcha = captchaService.get(CaptchaService.KEY_RESET, request.getSession().getId());
            if (StringUtils.isEmpty(serverCaptcha)) {
                return ResponseModel.error(HttpStatus.BAD_REQUEST, "验证码失效");
            }
            if (captchaService.verification(userFromVo.getCaptcha(), serverCaptcha)) {
                user.setPassword(userFromVo.getPassword());
                user.setLastPasswordResetDate(new Date());
                captchaService.delete(CaptchaService.KEY_RESET, request.getSession().getId());
                return ResponseModel.create(null, HttpStatus.OK, "修改密码成功");
            } else {
                return ResponseModel.error(HttpStatus.BAD_REQUEST, "验证码错误");
            }
        }
        return ResponseModel.error(HttpStatus.BAD_REQUEST, "账户和邮箱不匹配");
    }


    /**
     * 获取某个用户的粉丝
     *
     * @param id 用户id
     */
    @GetMapping("{id}/followers")
    public ResponseModel<?> userFollowers(@PathVariable("id") Long id) {
        User user = accountService.find(id);
        if (user == null) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "此用户不存在!");
        }
        return ResponseModel.ok(followService.getFollowers(user.getId()));

    }

    /**
     * 获取某某个用户关注的人
     *
     * @param id 用户id
     */
    @GetMapping("{id}/following")
    public ResponseModel<?> userFollowing(@PathVariable("id") Long id) {
        User user = accountService.find(id);
        if (user == null) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "此用户不存在!");
        }
        return ResponseModel.ok(followService.getFollowingsByUserId(user.getId()));
    }

    /**
     * 获取某个用户发表的post
     *
     * @param id 用户id
     */
    @GetMapping("{id}/posts")
    public ResponseModel<?> userPosts(@PathVariable("id") Long id) {
        User user = accountService.find(id);
        if (user == null) {
            return ResponseModel.error(HttpStatus.BAD_REQUEST, "此用户不存在!");
        }
        return ResponseModel.ok(postService.findPostsByUserId(user.getId()));
    }


}
